import java.util.Random;

public class Solution2 {
    public int[] smallestK(int[] nums, int k){
        int[] ret = new int[k];
        //使用快速选择算法
        quickSort(nums, 0, nums.length - 1, k);
        for(int i = 0; i < k; i++){
            ret[i] = nums[i];
        }
        return ret;
    }
    private void quickSort(int[] nums, int l, int r, int k){
        if(l >= r) return;
        //选择随机元素作为基准元素
        int key = nums[new Random().nextInt(r - l + 1) + l];
        //数组分三块
        int left = l - 1;
        int right = r + 1;
        int cur = l;
        while(cur < right){
            if(nums[cur] < key){
                swap(nums, ++left, cur++);
            }else if(nums[cur] == key){
                cur++;
            }else{
                swap(nums, --right, cur);
            }
        }
        //分情况讨论k的区域[l, left] [left + 1, right - 1] [right, r]
        if(k <= left - l + 1){
            quickSort(nums, l, left, k);
        }else if(k <= right - l){
            return;
        }else{
            quickSort(nums, right, r, k - (right - l));
        }
    }
    private void swap(int[] nums, int i , int j){
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
